package cn.agiledata.bank.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.ForwardConfig;

import cn.agiledata.bank.common.exception.BusinessException;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.login.form.LoginForm;
import com.vnv.infrastructure.action.IPBBaseAction;
import com.vnv.infrastructure.exception.IPBAppException;
import com.vnv.infrastructure.logic.IPBAppContext;
import com.vnv.infrastructure.logic.IPBAppContextHolder;
import com.vnv.infrastructure.util.IPBConstant;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: vnv Inc.</p>
 * 
 * 
 * @version 1.0
 */

/**
 * Base Action class with utility methods.
 * <br><br>
 * To enable the built-in access control feature, you need to specify the property for your action
 * in struts-config.xml as follows:
 * <pre>
 *    &lt;action path="/users" type="sample.action.user.UserAction" parameter="ipb_paging" name="userQuery"&gt;
 *       <b>&lt;set-property property="accessLevel" value="1"/&gt;</b>
 *       &lt;forward name="success" path="/users.jsp" redirect="false"/&gt;
 *    &lt;/action&gt;</pre>
 * The access level will be used to specify whether this user has permission to access this page.
 * Default value is 0. You could customize your access logic by overwriting
 * {@link #hasAccessPermission(int, javax.servlet.http.HttpServletRequest)}.
 * <br><br>
 * Once invalid session was detected, page will be forwarded to <b>'global_invalid_session'</b>
 * or <b>'global_denied_access'</b> as specified in struts-config.xml.
 */
public abstract class BaseMainAction extends IPBBaseAction implements Constant {
    // m_logger
    private static Log m_logger = LogFactory.getLog(BaseMainAction.class);

    public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
                                 HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;

        // log entry
        if(m_logger.isDebugEnabled()){
            m_logger.debug("Request accepted for session id: '" + request.getRequestedSessionId() + "' with request URI: '" + request.getRequestURI() + "'");
        }
        try {
            // check for application context
            IPBAppContext context = (IPBAppContext) request.getSession().getAttribute(IPBConstant.APP_CONTEXT_ATTR_NAME);
            if (context == null) {
                context = new IPBAppContext();
                request.getSession().setAttribute(IPBConstant.APP_CONTEXT_ATTR_NAME, context);
            }

            // set AppContext
            IPBAppContextHolder.set(context);

            String forwardName = _preProcess(mapping, actionForm, request, response);

            if (forwardName != null) {
                forward = mapping.findForward(forwardName);
                if (forward != null) {
                    // log exit
                    m_logger.debug("Request processed for session id: '" + request.getRequestedSessionId() + "' with request URI: '" + request.getRequestURI() + "'");
                    return forward;
                }
            }
            else if ((forward = _process(mapping, actionForm, request, response)) == null) {
                forward = preProcess(mapping, actionForm, request, response);
            }

            if (forward == null || forward.getName() == null) {
                forward = mapping.getInputForward();
                if (forward == null || forward.getName() == null) {
                    forward = mapping.findForward("global_error");
                }
            } else if (forward.getName().equals(Constant.FORWORD_NULL)) {
            	//不做任何处理，之前已有跳转，仅用于MainAction.logon()和TopAction.outRoute()
        		return null;
            }

            _postProcess(mapping, actionForm, request, response);
            postProcess(mapping, actionForm, request, response);
        }
        catch(BusinessException be) { //捕获业务系统级异常
        	if(actionForm instanceof LoginForm)	{
        		forward = mapping.findForward(((LoginForm)actionForm).getFrom());
        		ForwardConfig forwardConfig = mapping.findForwardConfig(((LoginForm)actionForm).getFrom());
                if(forwardConfig!=null && forwardConfig.getRedirect()) { //重定向方式
        			request.getSession().setAttribute(MESSAGE,be.getMessage());
        			//登录失败，把登录用户的email（及企业操作员）传给页面
        			if (((LoginForm)actionForm).getLogon_atype().equals("A")) {
        				request.getSession().setAttribute("email", ((LoginForm)actionForm).getLogon_person_email());
        			} else {
        				request.getSession().setAttribute("email", ((LoginForm)actionForm).getLogon_corp_email());
        				request.getSession().setAttribute("operator", ((LoginForm)actionForm).getLogon_corp_operator());
        			}
        			if (forward.getPath().startsWith("/outRoute.do")) {
            			request.getSession().setAttribute("showLogin","showLogin"); //用于显示登录层
            		}
        		} else { //forward方式
        			request.setAttribute(MESSAGE, be.getMessage());
        			if (forward.getPath().startsWith("/outRoute.do")) {
            			request.setAttribute("showLogin","showLogin"); //用于显示登录层
            		}
        		}
        	} else {
        		forward = mapping.findForward("failure");
        		if(mapping.findForwardConfig("failure").getRedirect()) {
        			request.getSession().setAttribute(MESSAGE,be.getMessage());
        		} else {
        			request.setAttribute(MESSAGE, be.getMessage());
        		}
        	}
        	
        }
        catch (IPBAppException ae) {
            //MainAction.activate()有可能抛MySpaceException，会调用到此处
        	handleAppException(mapping, actionForm, request, response, ae);
        	return getAppExceptionForward(mapping, actionForm, request, response, ae);
        }
        catch (Exception ie) {
        	//throw ie;
            //forward = _errorHandler(mapping, actionForm, request, response, ie);
        }
        finally {
            // reset AppContext
            IPBAppContextHolder.unset();
        }

        // log exit
        m_logger.debug("Request processed for session id: '" + request.getRequestedSessionId() + "' with request URI: '" + request.getRequestURI() + "'");

        return forward;
    }



}
